package com.xbongbong.workflow.service.strategy.node.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.config.enums.WorkflowTaskLogStatusEnum;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.exception.WorkflowException;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.help.SerialNoHelp;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.workflow.WorkflowDataPojo;
import com.xbongbong.paas.pojo.workflow.WorkflowExplainPojo;
import com.xbongbong.paas.service.WorkflowOperatorDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.WorkflowNodeUtil;
import com.xbongbong.paas.util.WorkflowUtil;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.domain.entity.WorkflowNodeEntity;
import com.xbongbong.workflow.enums.WorkflowNodeTypeEnum;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.FlowData;
import com.xbongbong.workflow.pojo.FlowDatas;
import com.xbongbong.workflow.pojo.WorkflowOperationsPojo;
import com.xbongbong.workflow.pojo.WorkflowProcessResultPojo;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.pojo.nodes.InsertRecordNode;
import com.xbongbong.workflow.service.help.WorkflowDataNodeHelp;
import com.xbongbong.workflow.service.operator.impl.WorkflowOperatorMainServiceImpl;
import com.xbongbong.workflow.service.operator.impl.WorkflowOperatorMainSubFormServiceImpl;
import com.xbongbong.workflow.service.operator.impl.WorkflowOperatorSubFormMainServiceImpl;
import com.xbongbong.workflow.service.operator.impl.WorkflowOperatorSubFormServiceImpl;
import com.xbongbong.workflow.service.strategy.node.AbstractWorkflowNodeStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 新建记录节点
 * @author 魏荣杰
 */
@Service
public class WorkflowNodeCreateStrategy extends AbstractWorkflowNodeStrategy {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowNodeCreateStrategy.class);

    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private WorkflowDataNodeHelp workflowDataNodeHelp;
    @Resource
    private SerialNoHelp serialNoHelp;
    @Resource
    private WorkflowOperatorMainSubFormServiceImpl workflowOperatorMainSubFormService;
    @Resource
    private WorkflowOperatorSubFormServiceImpl workflowOperatorSubFormService;
    @Resource
    private WorkflowOperatorSubFormMainServiceImpl workflowOperatorSubFormMainService;
    @Resource
    private WorkflowOperatorMainServiceImpl workflowOperatorMainService;
    @Resource
    private WorkflowOperatorDataService workflowOperatorDataService;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;

    @Override
    public String type() {
        return WorkflowNodeTypeEnum.CREATE_NODE.getName();
    }

    @Override
    public void before(WorkflowTransferPOJO workflowTransferPOJO) {
        super.before(workflowTransferPOJO);
    }

    @Override
    public WorkflowProcessResultPojo process(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity workflowNodeEntity, Long lastNodeId, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) {

        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Integer feeType = packageHelp.getFeeType(corpid);
            FlowDatas flowDatas = workflowTransferPOJO.getFlowDatas() == null ? new FlowDatas() : workflowTransferPOJO.getFlowDatas();
            Map<String, FlowData> nodeIdMap = Objects.isNull(flowDatas.getNodeIdMap()) ? new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY) : flowDatas.getNodeIdMap();
            FlowData empayFlowData = new FlowData(workflowNodeEntity.getFormId(), workflowNodeEntity.getAppId(), workflowNodeEntity.getMenuId(),
                    workflowNodeEntity.getSaasMark(), workflowNodeEntity.getBusinessType(), new ArrayList<>(), new ArrayList<>());
            nodeIdMap.put(workflowNodeEntity.getId().toString(), empayFlowData);
            flowDatas.setNodeIdMap(nodeIdMap);
            workflowTransferPOJO.setFlowDatas(flowDatas);
            if (!Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_VERSION_NOT_SUPPORT));
                return new WorkflowProcessResultPojo(true, false);
            }
            InsertRecordNode insertRecordNode = JSON.parseObject(workflowNodeEntity.getConfigData(), InsertRecordNode.class);
            if (CollectionsUtil.isNotEmpty(insertRecordNode.getOperations())) {
                // 当操作方式不为空时
                WorkflowDataPojo workflowDataPojo = workflowDataNodeHelp.getExplainMapByOperator(insertRecordNode, workflowNodeEntity, insertRecordNode.getOperations());
                Integer chooseDataSource = insertRecordNode.getChooseDataSource();
                PaasFormDataEntityExt paasFormDataEntity = WorkflowUtil.getFormData(workflowTransferPOJO);
                // 获取字段解释容器
                WorkflowExplainPojo workflowExplainPojo = WorkflowNodeUtil.getExplainMapByInsertNode(insertRecordNode, workflowNodeEntity, workflowDataPojo);
                List<JSONObject> list;
                if (Objects.equals(BasicConstant.ONE, chooseDataSource)) {
                   list = getInsertListByTriggerNode(insertRecordNode, workflowTransferPOJO, workflowExplainPojo, paasFormDataEntity, workflowNodeEntity, workflowDataPojo);
                } else {
                   list = getInsertList(insertRecordNode, workflowTransferPOJO, workflowExplainPojo, paasFormDataEntity, workflowNodeEntity, workflowDataPojo);
                }
                if (Objects.isNull(list) || list.isEmpty()) {
                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_PASS_ADD_DATA, BasicConstant.ZERO));
                    return new WorkflowProcessResultPojo(true, false);
                }
                // 获取编号
                List<String> serialNoList = serialNoHelp.getSerialNoListByFormId(workflowNodeEntity.getCorpid(), workflowNodeEntity.getFormId(), workflowExplainPojo.getTargetExplainMap(), list.size());
                // 增加 i18n 参数
                Locale locale = LocaleContextHolder.getLocale();
                String lang = locale.toString();
                List<Long> dataIdList = new ArrayList<>();
                List<String> errorList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    JSONObject jsonObject = list.get(i);
                    String serialNo = "";
                    if (CollectionsUtil.isNotEmpty(serialNoList)) {
                        serialNo = serialNoList.get(i);
                    }
                    FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                    Long appId = workflowNodeEntity.getAppId();
                    Long formId = workflowNodeEntity.getFormId();
                    Long menuId = workflowNodeEntity.getMenuId();
                    formDataAddDTO.setAppId(appId);
                    formDataAddDTO.setFormId(formId);
                    formDataAddDTO.setMenuId(menuId);
                    formDataAddDTO.setSerialNo(serialNo);
                    formDataAddDTO.setSaasMark(workflowNodeEntity.getSaasMark());
                    formDataAddDTO.setBusinessType(workflowNodeEntity.getBusinessType());
                    formDataAddDTO.setDataList(jsonObject);
                    formDataAddDTO.setIsBusinessRule(1);
                    formDataAddDTO.setCorpid(workflowNodeEntity.getCorpid());
                    formDataAddDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
                    formDataAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    try {
                        FormDataAddVO formDataAddVO = workflowOperatorDataService.add(formDataAddDTO);
                        dataIdList.add(formDataAddVO.getFormDataId());
                    } catch (XbbException e) {
                        // 插入失败
                        errorList.add(e.getMsg());
                    } catch (Exception e) {
                        // 插入失败
                        errorList.add(e.getMessage());
                        LOGGER.error("com.xbongbong.workflow.service.strategy.node.impl.WorkflowNodeCreateStrategy.process", e);
                    }
                }

                FlowData flowData = new FlowData(workflowNodeEntity.getFormId(), workflowNodeEntity.getAppId(), workflowNodeEntity.getMenuId(), workflowNodeEntity.getSaasMark(),
                        workflowNodeEntity.getBusinessType(), dataIdList, null);
                nodeIdMap.put(workflowNodeEntity.getId().toString(), flowData);
                flowDatas.setNodeIdMap(nodeIdMap);
                workflowTransferPOJO.setFlowDatas(flowDatas);
                if (CollectionsUtil.isEmpty(dataIdList)) {
                    String message = String.format(I18nMessageUtil.getMessage(MessageConstant.WORKFLOW_NODE_PASS_ADD_DATA), dataIdList.size()) + "；" + StringUtils.join(errorList, "，");
                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.SUSPEND, new WorkflowException(message));
                    return new WorkflowProcessResultPojo(false, false, true);
                } else {

                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_PASS_ADD_DATA, dataIdList.size()));
                }
            }
        } catch (WorkflowException e) {
            logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, e);
            return new WorkflowProcessResultPojo(false, false);
        } catch (XbbException e) {
            WorkflowException workflowException = new WorkflowException(e.getMsg());
            logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, workflowException);
            LOGGER.error("WorkflowNodeCreateStrategy.process error", e);
            return new WorkflowProcessResultPojo(false, false);
        } catch (Exception e) {
            LOGGER.error("WorkflowNodeCreateStrategy.process error", e);
            WorkflowException workflowException = new WorkflowException(e.getMessage());
            logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, workflowException);
            return new WorkflowProcessResultPojo(false, false);
        }
        return new WorkflowProcessResultPojo(true, false);
    }

    /**
     * 只有触发节点的数据进行的插入
     * @param insertRecordNode
     * @param workflowTransferPOJO
     * @param workflowExplainPojo
     * @param paasFormDataEntity
     * @param workflowNodeEntity
     * @param workflowDataPojo
     * @throws XbbException
     */
    private List<JSONObject> getInsertListByTriggerNode(InsertRecordNode insertRecordNode, WorkflowTransferPOJO workflowTransferPOJO, WorkflowExplainPojo workflowExplainPojo,
                                            PaasFormDataEntityExt paasFormDataEntity, WorkflowNodeEntity workflowNodeEntity, WorkflowDataPojo workflowDataPojo) throws XbbException {
        List<JSONObject> list = new ArrayList<>();
        try {
            Map<String, WorkflowOperationsPojo> operatorMap = workflowExplainPojo.getOperatorMap();
            Map<String, FieldAttrEntity> targetExplainMap = workflowExplainPojo.getTargetExplainMap();
            Map<String, Map<String, FieldAttrEntity>> thisExplainMap = workflowExplainPojo.getThisExplainMap();
            // 仅插入一条数据，数据来源于触发表单
            JSONObject result = new JSONObject();
            Integer maxSize = 0;
            Data workflowData = workflowTransferPOJO.getData();
            String corpid = workflowNodeEntity.getCorpid();

            FlowDatas flowDatas = workflowTransferPOJO.getFlowDatas();
            flowDatas = flowDatas ==null ? new FlowDatas() : workflowTransferPOJO.getFlowDatas();
            Map<String, FlowData> nodeIdMap = flowDatas.getNodeIdMap();
            nodeIdMap = nodeIdMap == null ? new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY) : nodeIdMap;
            Map<Long, PaasFormDataEntityExt> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            formDataMap.put(workflowData.getNodeId(), paasFormDataEntity);
            PaasFormDataEntityExt oldPaasFormData = null;
            if (Objects.equals(0, insertRecordNode.getEditedData()) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPOJO.getOperate())) {
                oldPaasFormData = WorkflowUtil.setData(workflowTransferPOJO.getOldData().getId(), corpid, workflowTransferPOJO.getOldData());
                formDataMap.put(workflowData.getNodeId(), oldPaasFormData);
            } else if (Objects.equals(2, insertRecordNode.getEditedData()) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPOJO.getOperate())) {
                // 触发事件编辑前数据
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE_BATCH.getType())) {
                    Data oldData = workflowTransferPOJO.getOldData();
                    paasFormDataEntity = WorkflowUtil.setData(oldData.getId(), corpid, oldData.getData(), oldData.getFormId(), oldData.getSaasMark(), oldData.getBusinessType());
                } else {
                    WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
                    paasFormDataEntity = WorkflowUtil.setData(workflowBackupDataEntity.getDataId(), corpid, workflowBackupDataEntity.getData(), workflowData.getFormId(), workflowData.getSaasMark(), workflowData.getBusinessType());
                }
                formDataMap.put(workflowData.getNodeId(), paasFormDataEntity);
            }
            Map<Long, JSONObject> dataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            Set<Long> workflowNodeList = workflowExplainPojo.getWorkflowNodeList();
            workflowNodeList.remove(workflowData.getNodeId());
            // 获取其他节点的数据，新建节点可以设置触发节点、获取单条数据节点
            getNodeDataMap(nodeIdMap, workflowNodeList, formDataMap, dataMap, corpid);
            Map<String, JSONArray> subResultMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Iterator<String> iterator = operatorMap.keySet().iterator();
            while (iterator.hasNext()) {
                String targetAttr = iterator.next();
                WorkflowOperationsPojo item = operatorMap.get(targetAttr);
                List<String> targetAttrList = ExplainUtil.getAttrByPoint(targetAttr);
                if (targetAttrList.size() == BasicConstant.TWO) {
                    targetAttr = targetAttrList.get(0);
                }
                // 触发节点的data数据需要放在循环内，因为此处会随着子表单的数据变动
                dataMap.put(workflowData.getNodeId(), paasFormDataEntity.getData());
                if (Objects.equals(0, insertRecordNode.getEditedData()) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPOJO.getOperate())) {
                    dataMap.put(workflowData.getNodeId(), oldPaasFormData.getData());
                }
                FieldAttrEntity targetField = targetExplainMap.get(targetAttr);
                if (Objects.isNull(targetField)) {
                    //  字段判断
                    throw new WorkflowException(BusinessRuleErrorCodeEnum.API_ERROR_261006.getMsg());
                }
                boolean thisIsSubForm = WorkflowNodeUtil.validateSubForm(item, thisExplainMap);
                boolean targetIsSubForm = Objects.equals(FieldTypeEnum.SUB_FORM.getType(), targetField.getFieldType());
                if (targetIsSubForm && thisIsSubForm) {
                    // 子表单字段赋值子表单字段
                    JSONObject jsonObject = workflowOperatorSubFormService.getInsertFieldListByDataNode(item,  workflowExplainPojo, targetField,
                            formDataMap, dataMap, insertRecordNode, workflowNodeEntity, workflowDataPojo, workflowTransferPOJO);
                    result.putAll(jsonObject);
                } else if (targetIsSubForm) {
                    // 主字段赋值给子表单字段
                    JSONObject jsonObject =  workflowOperatorSubFormMainService.getInsertFieldListByDataNode(item,  workflowExplainPojo, targetField,
                            formDataMap, dataMap, insertRecordNode, workflowNodeEntity, workflowDataPojo, workflowTransferPOJO);
                    result.putAll(jsonObject);
                } else if (thisIsSubForm) {
                    // 子字段赋值给主字段
                    // 获取字段解释，可能为null，只有动态值才有字段，公式和固定值是无固定的字段的
                    Map<String, JSONArray> resultDataMap = workflowOperatorMainSubFormService.getInsertFieldListByDataNode(item,  workflowExplainPojo, targetField,
                            formDataMap, dataMap, insertRecordNode, workflowNodeEntity, workflowDataPojo, workflowTransferPOJO);
                    if (Objects.nonNull(resultDataMap.get(item.getAttr()))
                            &&  maxSize< resultDataMap.get(item.getAttr()).size()) {
                        maxSize = resultDataMap.get(item.getAttr()).size();
                    }
                    subResultMap.put(item.getAttr(), resultDataMap.get(item.getAttr()));
                } else {
                    // 主赋值主
                    // 获取字段解释，可能为null，只有动态值才有字段，公式和固定值是无固定的字段的
                    JSONObject jsonObject = workflowOperatorMainService.getInsertFieldListByDataNode(item,  workflowExplainPojo, targetField,
                            formDataMap, dataMap, insertRecordNode, workflowNodeEntity, workflowDataPojo, workflowTransferPOJO);
                    result.putAll(jsonObject);
                }
            }
            list = DataUtil.getData(subResultMap, maxSize, result);
        } catch (XbbException e) {
            throw e;
        }  catch (Exception e) {
            LOGGER.error("com.xbongbong.workflow.service.strategy.node.impl.WorkflowNodeCreateStrategy.getInsertListByTriggerNode error：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return list;
    }

    /**
     * 既有触发节点，又有获取据节点的插入
     * @param insertRecordNode
     * @param workflowTransferPOJO
     * @param workflowExplainPojo
     * @param paasFormDataEntity
     * @param workflowNodeEntity
     * @param workflowDataPojo
     * @throws XbbException
     */
    private List<JSONObject> getInsertList(InsertRecordNode insertRecordNode, WorkflowTransferPOJO workflowTransferPOJO, WorkflowExplainPojo workflowExplainPojo,
                               PaasFormDataEntityExt paasFormDataEntity, WorkflowNodeEntity workflowNodeEntity, WorkflowDataPojo workflowDataPojo) throws XbbException {
        List<JSONObject> list = new ArrayList<>();
        try {
            Map<String, FieldAttrEntity> targetExplainMap = workflowExplainPojo.getTargetExplainMap();
            Map<String, Map<String, FieldAttrEntity>> thisExplainMap = workflowExplainPojo.getThisExplainMap();
            Map<String, WorkflowOperationsPojo> operatorMap = workflowExplainPojo.getOperatorMap();

            Data workflowData = workflowTransferPOJO.getData();
            String corpid = workflowNodeEntity.getCorpid();
            Long workflowNodeId = insertRecordNode.getWorkflowNodeId();
            FlowDatas flowDatas = workflowTransferPOJO.getFlowDatas();
            flowDatas = flowDatas ==null ? new FlowDatas() : workflowTransferPOJO.getFlowDatas();
            Map<String, FlowData> nodeIdMap = flowDatas.getNodeIdMap();
            nodeIdMap = nodeIdMap == null ? new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY) : nodeIdMap;
            FlowData flowData = nodeIdMap.get(workflowNodeId.toString());
            if (Objects.nonNull(flowData) && CollectionsUtil.isNotEmpty(flowData.getIds())) {
                List<PaasFormDataEntityExt> formDataList = formDataHelp.getByDataIdList(flowData.getIds(), flowData.getBusinessType(), flowData.getSaasMark(), flowData.getFormId(), corpid);
                Set<Long> workflowNodeList = workflowExplainPojo.getWorkflowNodeList();
                // 移掉获取多条数据的节点
                workflowNodeList.remove(workflowNodeId);
                // 移掉触发节点
                workflowNodeList.remove(workflowData.getNodeId());
                Map<Long, PaasFormDataEntityExt> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                formDataMap.put(workflowData.getNodeId(), paasFormDataEntity);
                // data里面的字段，当然，也会当做子表单的容器
                Map<Long, JSONObject> dataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

                // 获取其他节点的数据，新建节点可以设置触发节点、获取单条数据节点、获取多条数据节点
                getNodeDataMap(nodeIdMap, workflowNodeList, formDataMap, dataMap, corpid);
                PaasFormDataEntityExt oldPaasFormData = null;
                if (Objects.equals(0, insertRecordNode.getEditedData()) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPOJO.getOperate())) {
                   oldPaasFormData = WorkflowUtil.setData(workflowTransferPOJO.getOldData().getId(), corpid, workflowTransferPOJO.getOldData());
                   formDataMap.put(workflowData.getNodeId(), oldPaasFormData);
                } else if (Objects.equals(2, insertRecordNode.getEditedData()) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPOJO.getOperate())) {
                    // 触发事件编辑前数据
                    if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE_BATCH.getType())) {
                        Data oldData = workflowTransferPOJO.getOldData();
                        paasFormDataEntity = WorkflowUtil.setData(oldData.getId(), corpid, oldData.getData(), oldData.getFormId(), oldData.getSaasMark(), oldData.getBusinessType());
                    } else {
                        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
                        paasFormDataEntity = WorkflowUtil.setData(workflowBackupDataEntity.getDataId(), corpid, workflowBackupDataEntity.getData(), workflowData.getFormId(), workflowData.getSaasMark(), workflowData.getBusinessType());
                    }

                }
                Integer maxSize = 0;
                for (PaasFormDataEntityExt item : formDataList) {
                    JSONObject result = new JSONObject();

                    formDataMap.put(workflowNodeId, item);
                    // 触发节点的data数据需要放在循环内，因为此处会随着子表单的数据变动
                    dataMap.put(workflowNodeId, item.getData());
                    Map<String, JSONArray> subResultMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Iterator<String> iterator = operatorMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        WorkflowOperationsPojo workflowOperationsPojo = operatorMap.get(key);
                        String targetAttr = workflowOperationsPojo.getAttr();
                        List<String> targetAttrList = ExplainUtil.getAttrByPoint(targetAttr);
                        if (targetAttrList.size() == BasicConstant.TWO) {
                            targetAttr = targetAttrList.get(0);
                        }
                        dataMap.put(workflowData.getNodeId(), paasFormDataEntity.getData());
                        if (Objects.equals(0, insertRecordNode.getEditedData()) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPOJO.getOperate())) {
                            // 取编辑前的数据
                            dataMap.put(workflowData.getNodeId(), oldPaasFormData.getData());
                        }
                        FieldAttrEntity targetField = targetExplainMap.get(targetAttr);
                        if (Objects.isNull(targetField)) {
                            throw new WorkflowException(BusinessRuleErrorCodeEnum.API_ERROR_261006.getMsg());
                        }
                        boolean thisIsSubForm = WorkflowNodeUtil.validateSubForm(workflowOperationsPojo, thisExplainMap);
                        boolean targetIsSubForm = Objects.equals(FieldTypeEnum.SUB_FORM.getType(), targetField.getFieldType());
                        if (targetIsSubForm && thisIsSubForm) {
                            // 子表单字段赋值子表单字段
                            JSONObject jsonObject = workflowOperatorSubFormService.getInsertFieldListByDataNode(workflowOperationsPojo, workflowExplainPojo, targetField, formDataMap, dataMap,
                                    insertRecordNode, workflowNodeEntity, workflowDataPojo, workflowTransferPOJO);
                            result.putAll(jsonObject);
                        } else if (targetIsSubForm) {
                            // 主字段赋值给子表单字段
                            JSONObject jsonObject = workflowOperatorSubFormMainService.getInsertFieldListByDataNode(workflowOperationsPojo, workflowExplainPojo, targetField, formDataMap, dataMap,
                                    insertRecordNode, workflowNodeEntity, workflowDataPojo, workflowTransferPOJO);
                            result.putAll(jsonObject);
                        } else if (thisIsSubForm) {
                            // 子字段赋值给主字段

                            Map<String, JSONArray> resultDataMap = workflowOperatorMainSubFormService.getInsertFieldListByDataNode(workflowOperationsPojo, workflowExplainPojo, targetField, formDataMap, dataMap,
                                    insertRecordNode, workflowNodeEntity, workflowDataPojo, workflowTransferPOJO);
                            if (Objects.nonNull(resultDataMap.get(targetAttr))
                                    &&  maxSize< resultDataMap.get(targetAttr).size()) {
                                maxSize = resultDataMap.get(targetAttr).size();
                            }
                            subResultMap.put(targetAttr, resultDataMap.get(targetAttr));
                        } else {
                            // 主赋值主
                            // 获取字段解释，可能为null，只有动态值才有字段，公式和固定值是无固定的字段的
                            JSONObject jsonObject = workflowOperatorMainService.getInsertFieldListByDataNode(workflowOperationsPojo, workflowExplainPojo, targetField, formDataMap, dataMap,
                                    insertRecordNode, workflowNodeEntity, workflowDataPojo, workflowTransferPOJO);
                            result.putAll(jsonObject);
                        }
                    }
                    List<JSONObject> resultList = DataUtil.getData(subResultMap, maxSize, result);
                    list.addAll(resultList);
                }
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.workflow.service.strategy.node.impl.WorkflowNodeCreateStrategy.getInsertList error：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return list;
    }


    /**
     * 获取其他节点的数据
     * @param nodeIdMap
     * @param workflowNodeList
     * @param formDataMap
     * @param dataMap
     * @param corpid
     */
    private void getNodeDataMap(Map<String, FlowData> nodeIdMap, Set<Long> workflowNodeList, Map<Long, PaasFormDataEntityExt> formDataMap, Map<Long, JSONObject> dataMap, String corpid) {
        if (CollectionUtils.isEmpty(workflowNodeList)) {
            return;
        }
        workflowNodeList.forEach(item->{
            FlowData singleDataNodeFlowData = nodeIdMap.get(item.toString());
            if (Objects.isNull(singleDataNodeFlowData)) {
                return;
            }
            List<PaasFormDataEntityExt> targetDataList = formDataHelp.getByDataIdList(singleDataNodeFlowData.getIds(), singleDataNodeFlowData.getBusinessType(),
                    singleDataNodeFlowData.getSaasMark(), singleDataNodeFlowData.getFormId(), corpid);
            if (CollectionUtils.isNotEmpty(targetDataList)) {
                PaasFormDataEntityExt paasFormDataEntityExt = targetDataList.get(0);
                formDataMap.put(item, paasFormDataEntityExt);
                dataMap.put(item, paasFormDataEntityExt.getData());
            } else {
                formDataMap.put(item, new PaasFormDataEntityExt());
                dataMap.put(item, new JSONObject());
            }
        });
    }
   

    @Override
    public void after(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity workflowNodeEntity) {
        super.after(workflowTransferPOJO, workflowNodeEntity);
    }

    @Override
    public void check() {
        super.check();
    }


    @Override
    public void logger(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity nodeEntity, WorkflowTaskLogStatusEnum workflowTaskLogStatusEnum, WorkflowException workflowException) {
        super.logger(workflowTransferPOJO, nodeEntity, workflowTaskLogStatusEnum, workflowException);
    }
}
